// var BASEURL = 'http://192.168.31.250';
var BASEURL = '';
var applyInfo = {};
const uploadTips = {
    idcardTip: "请选择身份证照片",
    idcardSuccess: "身份证上传成功",
    marriageTip: "请选择结婚证照片",
    marriageSuccess: "结婚证上传成功",
}
var option = {
    lines: 9, // 花瓣数目
    length: 1, // 花瓣长度
    width: 10, // 花瓣宽度
    radius: 15, // 花瓣距中心半径
    shadow: true,
    opacity: 1 / 8
};

var spinner = new Spinner(option);
var steps = [];
var stepIndex = 0;//进度步骤
var personTypeId = 1;//免费类型id
$(document).ready(function () {
    $('#idcard').show();
    $("#marriage_cert").hide();
    $('#military_cert').hide();
    $('#live_cert').hide();
    $('#other_desc').hide();
    $('#husband_idcard').hide();
//            $('#submitBtn').hide();
    resetSelect($('#province'), '', 10);
    //初始化进度条
    steps = $(".step");
    setStep(stepIndex);
    //初始化上传提示
    for (var i = 1; i < 8; i++) {
        setUploadStatus(i, 0);
    }
    //隐藏优惠券领取
    $('#couponBox').hide();
    $('#applyModal').on('hidden.bs.modal', function (e) {
        // window.location.reload();
    })

})
function addImg(type) {
    var fileId = '#file' + type;
    $(fileId).click()
}
function fileChange(type) {
    var fileId = '#file' + type;
    var imgPreviewId = '#imgPreview' + type;
    var imgFile = $(fileId)[0].files[0];
    var fr = new FileReader();
    fr.onload = function () {
        $(imgPreviewId).attr('src', fr.result);
    };
    fr.readAsDataURL(imgFile);
}
function setUploadStatus(type, status) {//status:1成功,0待上传
    var typeId;
    switch (type) {
        case 1:
            typeId = 'idcard';
            break;
        case 2:
            typeId = '';
            break;
        case 3:
            typeId = 'marriage';
            break;
        case 4:
            typeId = 'husband';
            break;
        case 5:
            typeId = 'military';
            break;
        case 6:
            typeId = 'live';
            break;
        case 7:
            typeId = 'household';
            break;
        default:
    }
    if (typeId) {
        if (status === 1) {
            $('.' + typeId + '_success').show();
            $('.' + typeId + '_sel').hide();
        } else {
            $('.' + typeId + '_success').hide();
            $('.' + typeId + '_sel').show();
        }
    }
}
function upload(type) {//type: 1身份证 2身份证背面-暂不上传 3结婚证 4丈夫身份证 5军官证 6居住证 7户口本
    var fileId = '#file' + type;
    const formData = new FormData();
    var fileData = $(fileId)[0].files[0]
    if (!fileData) {
        alert('请添加证件照片!')
        return;
    }
    //验证手机号码格式
    var pattern2 = /^1[3456789]\d{9}$/;
    var mobNo2 = pattern2.test($('.mobile').val());
    if(!mobNo2){
        alert('请输入正确的手机号码！');
        return false;
    }
    formData.append('mobile', $('.mobile').val());
    formData.append('file', fileData);
    var target = document.getElementById('uploadForm' + type);
    spinner.spin(target);
    formData.append("imgType", type);
    formData.append('presonType', personTypeId);
    if (applyInfo.id) {
        formData.append('id', applyInfo.id);
    }
    $.ajax({
        url: BASEURL + "/csfy/intf.do?method=imageUpload",
        type: "POST",
        data: formData,
        timeout: 150000,
        processData: false,
        contentType: false,
        success: function (data) {
            var alertMsg = data.msg ==='success'?'上传成功':data.msg;
            alert(alertMsg);
            if (data.rows) {
                setUploadStatus(type, 1);
                switch (type) {
                    case 1:
                        applyInfo.name = data.rows.name;
                        $('#idcard_name').text(data.rows.name);
                        applyInfo.sex = data.rows.sex;
                        $('#idcard_sex').text(data.rows.sex);
                        applyInfo.nation = data.rows.nation;
                        $('#idcard_nation').text(data.rows.nation);
                        applyInfo.birth = data.rows.birth;
                        $('#idcard_birth').text(data.rows.birth);
                        applyInfo.address = data.rows.address;
                        $('#idcard_address').text(data.rows.address);
                        applyInfo.cardFrontImgUrl = data.rows.cardFrontImgUrl;
                        applyInfo.selfId = data.rows.id;//个人身份证id
                        applyInfo.id = data.rows.id;//用户信息id
                        $('#idcard_id').text(data.rows.id);
                        break;
                    case 2:
                        applyInfo.cardBackImgUrl = data.rows.cardBackImgUrl;
                        break;
                    case 3:
                        applyInfo.marriageImgUrl = data.rows.marriageImgUrl;
                        break;
                    case 4:
                        applyInfo.cardMateImgUrl = data.rows.cardMateImgUrl;
                        applyInfo.husbandId = data.rows.id;
                        break;
                    case 5:
                        applyInfo.officerImgUrl = data.rows.officerImgUrl;
                        applyInfo.militaryId = data.rows.id;
                        if (!applyInfo.selfId) {
                            applyInfo.id = data.rows.id;
                        }
                        break;
                    case 6:
                        applyInfo.name = data.rows.name;
                        $('#live_name').text(data.rows.name);
                        applyInfo.sex = data.rows.sex;
                        $('#live_sex').text(data.rows.sex);
                        applyInfo.nation = data.rows.nation;
                        $('#live_nation').text(data.rows.nation);
                        applyInfo.birth = data.rows.birth;
                        $('#live_birth').text(data.rows.birth);
                        applyInfo.address = data.rows.address;
                        $('#live_address').text(data.rows.address);
                        applyInfo.residencePermitImgUrl = data.rows.residencePermitImgUrl;
                        applyInfo.liveId = data.rows.id;
                        applyInfo.id = data.rows.id;
                        $('#live_id').text(data.rows.id);
                        break;
                    default:
                }
                checkUploadStep();
            }
            spinner.spin();
        },
        error: function (err) {
            alert('网络错误!');
            spinner.spin();
        }
    });
}
function checkUploadStep() {
    switch (personTypeId) {
        case 1:
            if (!applyInfo.cardFrontImgUrl) {
                return false;
            }
            break;
        case 2:
            if (!applyInfo.cardFrontImgUrl || !applyInfo.cardMateImgUrl || !applyInfo.marriageImgUrl) {
                return false;
            }
            break;
        case 3:
            if (!applyInfo.officerImgUrl) {
                return false;
            }
            break;
        case 4:
            if (!applyInfo.cardFrontImgUrl || !applyInfo.officerImgUrl || !applyInfo.marriageImgUrl) {
                return false;
            }
            break;
        case 5:
            if (!applyInfo.cardFrontImgUrl || !applyInfo.residencePermitImgUrl) {
                return false;
            }
            break;
        case 6:
            if (!applyInfo.cardFrontImgUrl) {
                return false;
            }
            break;
        default:
    }
    stepIndex = 1;
    setStep(1);
    if (couponInfos.length == 0 && unreceivedCouponInfos.length == 0) {
        $('#submitBtn').show();
    }
    return true;
}
function checkFormStep() {
    stepIndex = 2;
    setStep(2);
}
function confirm() {
    var applyInfo = window.applyInfo || {};
    const data = {
        name: applyInfo.name,
        sex: 1,
        nation: applyInfo.nation,
        birth: applyInfo.birth,
        id: applyInfo.id,
        address: applyInfo.address,
        imageUrl: applyInfo.imageUrl,
        presonType: 1,
        permanentAddr: '湖南省,长沙市,长沙县'
    };
    $.ajax({
        url: BASEURL + "/csfy/intf.do?method=savePresonInfo",
        type: "post",
        data: data,
        timeout: 150000,
        dataType: "json",
        success: function (data) {
            alert(data.msg);
            if (data.rows) {

            }
        },
        error: function (err) {
            alert('网络错误!');
        }

    });
}
//优惠券选择
function couponSel(id) {
    var checkId = '#customCheck' + id;
    $(checkId).trigger('click');
}
//省市区
function resetSelect(jq, parentId, defaultIdx) {
    var url = BASEURL+'/csfy/intf.do?method=getAddrs';
    if (parentId) {
        url = url + '&parentId=' + parentId;
    }
    var jqId = '#' + jq.attr('id');
    $.getJSON(url, function (data) {
        if (data.msg === 'success') {
            jq.empty();
            $.each(data.rows, function (i, item) {
                var option = $('<option></option>');
                option.attr('value', item['code']);
                option.text(item['name']);
                jq.append(option);
            });
            if (defaultIdx) {
                jq.get(0).selectedIndex = defaultIdx;
            }

            if (jqId) {
                addressChange(jqId);
            }
            jq.selectpicker('refresh');
        }
    });
}
function addressChange(id) {
    var code = $(id).children('option:selected').attr('value')
    switch (id) {
        case '#province':
        {
            var defaultIdx = undefined;
            if (code == 43) {
                defaultIdx = 8;
            }
            resetSelect($('#city'), code, defaultIdx);
            $('#county').empty();
            $('#town').empty();
            $('#county').selectpicker('refresh');
            $('#town').selectpicker('refresh');
            break;
        }
        case '#city':
        {
            resetSelect($('#county'), code);
            $('#town').empty();
            $('#town').selectpicker('refresh');
            break;
        }
        case '#county':
        {
            resetSelect($('#town'), code);
            break;
        }
        case '#town':
        {
            break;
        }
    }
}

function pregnancyChange() {
    var type = $('#pregnancy').children('option:selected').val();
    var typeId = $('#pregnancy').children('option:selected').attr('type_id');
    var pregnancy = typeId;
    applyInfo.pregnancy = pregnancy;
}
var couponInfos = [];//已领取
var unreceivedCouponInfos = [];//未领取
function submit() {
    var pattern2 = /^1[3456789]\d{9}$/;
    var mobNo2 = pattern2.test($('.mobile').val());
    if(!mobNo2){
        alert('请输入正确的手机号码！');
        return false;
    }
    if(applyInfo.id == undefined){
        var pattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        var mobNo = pattern.test($('.idCard').val());
        if(!mobNo){
            alert('请输入正确的身份证号码！');
            return false;
        }
        var postData = {
            name:$('.personName').val(),
            nation:$('.minzu').val(),
            id:$('.idCard').val(),
            address:$('.hjAddress').val(),
            presonType:personTypeId,
            province:$('#province option:selected').text(),
            city:$('#city option:selected').text(),
            country:$('#county option:selected').text(),
            town:$('#town option:selected').text(),
            mobile:$('.mobile').val()
        }
        console.log(postData);
        if(postData.name == ''){
            alert("请输入姓名！");
            return false;
        }
        if(postData.nation == ''){
            alert("请输入民族！");
            return false;
        }
        if(postData.id == ''){
            alert("请输入身份证号码！");
            return false;
        }
        if(postData.address == ''){
            alert("请输入户籍地址！");
            return false;
        }
        applyInfo.id = $(".idCard").val();
        $.ajax({
            url: BASEURL + "/csfy/intf.do?method=savePresonInfo",
            type: "post",
            data: postData,
            timeout: 150000,
            dataType: "json",
            success: function (data) {
                if (data.msg === 'success') {
                    var url = BASEURL + '/csfy/intf.do?method=getDetailPresonInfo&type=' + personTypeId + '&id=' + applyInfo.id;
                    $.ajax({
                        url: url,
                        type: "post",
                        data: {},
                        timeout: 150000,
                        dataType: "json",
                        processData: false,
                        contentType: false,
                        success: function (data) {
                            if (data.msg === 'success') {
                                unreceivedCouponInfos = data.rows.unreceivedCouponInfos;
                                couponInfos = data.rows.couponInfos;
                                refreshCouponInfos(unreceivedCouponInfos, 0);
                                refreshCouponInfos(couponInfos, 1);
                                $('#submitBtn').hide();
                                $('#couponBox').show();
                            } else {
                                alert('抱歉,出错了');
                            }
                        },
                        error: function (err) {
                            alert('网络错误!');
                        }
                    });
                }
            },
            error: function (err) {
                alert('网络错误!');
            }

        });
    }else {
        if (!applyInfo.id) {
            alert('请正确上传证件信息!');
            return false;
        }
        var url = BASEURL + '/csfy/intf.do?method=getDetailPresonInfo&type=' + personTypeId + '&id=' + applyInfo.id;

        $.ajax({
            url: url,
            type: "post",
            data: {},
            timeout: 150000,
            dataType: "json",
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.msg === 'success') {
                    unreceivedCouponInfos = data.rows.unreceivedCouponInfos;
                    couponInfos = data.rows.couponInfos;
                    refreshCouponInfos(unreceivedCouponInfos, 0);
                    refreshCouponInfos(couponInfos, 1);
                    $('#submitBtn').hide();
                    $('#couponBox').show();
                } else {
                    alert('抱歉,出错了');
                }
            },
            error: function (err) {
                alert('网络错误!');
            }
        });
    }
}
function refreshCouponInfos(couponInfos, status) {//status:0未领取列表,1已领取列表
    if (status == 0) {
        var couponsStr = '';
        for (const key in couponInfos) {
            var coupon = couponInfos[key];
            if (coupon) {
                if(coupon.type !=6 && coupon.type !=3){//屏蔽地中海和HPV
                    var imgStr = `<img onclick="couponSel(${key})" style="width:400px;height:100px;" src="${coupon.couponImg}" data-src="holder.js/400x100" alt="" class="custom-control-label"></img>`;
//                        var checkboxStr = `<input type="checkbox" class="custom-control-input" id="customCheck${key}">`
//                        var taishu = '<div class="form-inline" style="margin: 10px 0"><label>胎数：</label><select onchange="pregnancyChange()" id="pregnancy" class="form-control"><option type_id="0">请选择</option><option type_id="1">单胎</option><option type_id="2">双胎</option><option type_id="3">三胎</option></select></div>'
//                        var riqi = '<div><label>末次月经时间：</label><input type="date" /></div>';
                    var lingqu = '<div style="width:100px;margin-left:auto;margin-right:auto;"><button class="btn btn-primary" id="applyBtn" onclick="apply(' + coupon.type +')" style="cursor:pointer;" type="button">领取</button></div>';
                    var lineStr = '<div style="height:10px;"></div>';
                    couponsStr = couponsStr + imgStr + lingqu + lineStr;
                }
            }
        }
        if (!couponInfos || couponInfos.length == 0) {
            $('#applyBtn').hide();
            couponsStr = '<div>无可领取的免费券</div>';
        }
        $('#couponInfos').html(couponsStr);
    } else {
        var couponsStr = '';
        for (const key in couponInfos) {
            var coupon = couponInfos[key];
            if (coupon) {
                if(coupon.type !=6 && coupon.type !=3){//屏蔽地中海和HPV
                    var imgStr = `<img onclick="couponSel(${key})" style="width:400px;height:100px;" src="${coupon.couponImg}" data-src="holder.js/400x100" alt="" class="custom-control-label"></img>`;
                    var lineStr = '<div style="height:10px;"></div>';
                    couponsStr = couponsStr + imgStr + lineStr;
                }
            }
        }
        $('#couponInfos_received').html(couponsStr);
    }
}
var couponLabels = ['HPV免费券', 'NIPT免费券', '产前血清学筛查', '新生儿疾病筛查', '耳聋基因检测'];
var jtype = '';//优惠劵类型
var userId = '';//用户身份证
function apply(type) {///csfy/intf.do?method=addCouponInfo
    console.log(type);
    console.log(applyInfo);
    jtype = type;
    userId = applyInfo.id;
    var tip = '您已为本地常住居民代领免费券:';
    if(type == '3'){
        $.ajax({
            url: BASEURL + "/csfy/intf.do?method=addCouponInfo&type=" + type + '&id=' + applyInfo.id,
            type: "post",
            data: {},
            timeout: 150000,
            dataType: "json",
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.msg === 'success') {
                    checkUploadStep();
//                            couponInfos = data.rows.couponInfos;
//                            unreceivedCouponInfos = data.rows.unreceivedCouponInfos;
                    submit();
//                            refreshCouponInfos(unreceivedCouponInfos, 0);
//                            refreshCouponInfos(couponInfos, 1);
                    $('#modalTip').text('您已为本地常住居民代领免费券');
                    $('#applyModal').modal('show');
                } else {
                    alert('抱歉,出错了');
                }
            },
            error: function (err) {
                alert('网络错误!');
            }
        });
    }else {
        $(".zhezhao").css('display','block');
        $(".alertDiv").css('display','block');
    }
    if(type == '1' || type == '5'){
        $(".taishu").css('display','block');
    }
//            var total = 0;
//            var applyCoupons = [];
//            for (var i = 0; i < 5; i++) {
//                var checked = $('#customCheck' + i).prop('checked');
//                if (!checked) {
//                    continue;
//                }
//                total++;
//                // tip = tip + couponLabels[i]+'1张';
//                tip = tip + unreceivedCouponInfos[i].couponeName + '1张';
//                applyCoupons.push(unreceivedCouponInfos[i]);
//                if (i != 4) {
//                    tip = tip + ',';
//                }
//            }
//            if (total === 0) {
//                alert('请先选择要申请的优惠券')
//                return;
//            }
//            $('#modalTip').text(tip);
//            $('#applyModal').modal('show');
//            for (var k in applyCoupons) {
//                var coupon = applyCoupons[k];
//                console.log(coupon);
//                console.log(applyInfo);
//
//            }
}
//弹窗确定领取优惠券
function commit() {
    var taishu = taishu = $('#pregnancy').children('option:selected').attr('type_id');
    var dateStr = $('.yjDate').val();
    if((jtype == '1' || jtype == '5') && taishu == ''){
        alert("请选择胎数");
        return false;
    }
    if((jtype == '1' || jtype == '2' || jtype == '4' || jtype == '5' || jtype == '6') && dateStr == ''){
        alert("请输入末次月经时间");
        return false;
    }
    if(jtype == '2' || jtype == '4' || jtype == '6'){
        taishu = '';
    }
    console.log("jtype:"+jtype+"----"+"userId:"+userId+"----"+"taishu:"+taishu+"----"+"lmp:"+dateStr);
    $.ajax({
        url: BASEURL + "/csfy/intf.do?method=addCouponInfo&type=" + jtype + '&id=' + userId + '&num=' + taishu + '&lmp=' + dateStr,
        type: "post",
        data: {},
        timeout: 150000,
        dataType: "json",
        processData: false,
        contentType: false,
        success: function (data) {
            if (data.msg === 'success') {
                checkUploadStep();
//                        couponInfos = data.rows.couponInfos;
//                        unreceivedCouponInfos = data.rows.unreceivedCouponInfos;
//                        refreshCouponInfos(unreceivedCouponInfos, 0);
//                        refreshCouponInfos(couponInfos, 1);
                submit();
                $(".zhezhao").css('display','none');
                $(".alertDiv").css('display','none');
                $(".taishu").css('display','none');
                $('#modalTip').text('您已为本地常住居民代领免费券');
                $('#applyModal').modal('show');
            } else {
                alert('抱歉,出错了');
            }
        },
        error: function (err) {
            alert('网络错误!');
        }
    });
}
//关闭遮罩
function closeZhezhao() {
    $(".zhezhao").css('display','none');
    $(".alertDiv").css('display','none');
    $(".taishu").css('display','none');
}
function couponTypeChange() {
    var type = $('#couponType').children('option:selected').val();
    var typeId = $('#couponType').children('option:selected').attr('type_id');
    personTypeId = typeId;
    switch (typeId) {
        case "1":
        {
            $('#idcard').show();
            $("#marriage_cert").hide();
            $('#military_cert').hide();
            $('#live_cert').hide();
            $('#other_desc').hide();
            $('#husband_idcard').hide();
            $('#household_register').show();
            $('#address_tip').show();
            break;
        }
        case "2":
        {
            $('#idcard').show();
            $("#marriage_cert").show();
            $('#military_cert').hide();
            $('#live_cert').hide();
            $('#other_desc').hide();
            $('#husband_idcard').show();
            $('#household_register').show();
            $('#address_tip').show();
            break;
        }
        case "6":
        {
            $('#idcard').hide();
            $("#marriage_cert").hide();
            $('#military_cert').show();
            $('#live_cert').hide();
            $('#other_desc').hide();
            $('#husband_idcard').hide();
            $('#household_register').hide();
            $('#address_tip').hide();
            break;
        }
        case "4":
        {
            $('#idcard').show();
            $("#marriage_cert").show();
            $('#military_cert').hide();
            $('#live_cert').hide();
            $('#other_desc').hide();
            $('#husband_idcard').show();
            $('#household_register').hide();
            $('#address_tip').hide();
            break;
        }
        case "3":
        {
            $('#idcard').hide();
            $("#marriage_cert").hide();
            $('#military_cert').hide();
            $('#live_cert').show();
            $('#other_desc').hide();
            $('#husband_idcard').hide();
            $('#household_register').hide();
            $('#address_tip').hide();
            break;
        }
        case "5":
        {
            $('#idcard').show();
            $("#marriage_cert").hide();
            $('#military_cert').hide();
            $('#live_cert').hide();
            $('#other_desc').show();
            $('#husband_idcard').hide();
            $('#household_register').hide();
            $('#address_tip').hide();
            break;
        }
        default:
        {

        }
    }
}
// 进度条
$(".step-icon").click(function () {
    var me = this;
    stepIndex = $(me).parents(".step").index();
    setStep(stepIndex);
});
function setStep(stepIdx) {
    $(steps).removeClass("is-sucess");
    $(steps).removeClass("last-sucess");
    for (var i = 0; i <= stepIdx; i++) {
        var step = steps[i];
        if (i < stepIdx) {
            $(step).addClass("is-sucess");
        }
        else {
            $(step).addClass("last-sucess");
        }
    }
}
function clearSteps() {
    stepIndex = -1;
    setStep(stepIndex);
}
function addStep(addnum) {
    if (!addnum) { addnum = 1 }
    stepIndex += addnum;
    setStep(stepIndex);
}


//获取当前登录用户信息
$(document).ready(function () {
    $.ajax({
        method: 'POST',
        url: '/csfy/intf.do',
        data: { method: 'getLoginUserInfo' },
        success: res => {
        if (res.code == 10086) {
//                        window.location.href = "/csfy/index.do"
        alert("请重新登录！");
    } else {
        if (res.code == 200) {
            $(".username").html(res.rows.userName);
        }
    }
}
})
})